package com.ytjj.qmyx.mall.utils;


import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.github.binarywang.wxpay.config.WxPayConfig;
import com.github.binarywang.wxpay.constant.WxPayConstants;
import com.github.binarywang.wxpay.service.WxPayService;
import com.github.binarywang.wxpay.service.impl.WxPayServiceImpl;
import com.ytjj.qmyx.mall.model.PayConfig;
import com.ytjj.qmyx.mall.model.dto.WxPayDto;
import org.apache.commons.lang3.StringUtils;

import javax.servlet.http.HttpServletRequest;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;

public class WxPayServiceUtil {
    public static WxPayService getWxPayService(PayConfig payConfig){
        WxPayConfig wxPayConfig = new WxPayConfig();
        wxPayConfig.setAppId(StringUtils.trimToNull(payConfig.getAppid()));
        wxPayConfig.setMchId(StringUtils.trimToNull(payConfig.getMchId()));
        wxPayConfig.setMchKey(StringUtils.trimToNull(payConfig.getWxKey()));
        if(StringUtils.isNotBlank(payConfig.getSubAppId())) {
            wxPayConfig.setSubAppId(StringUtils.trimToNull(payConfig.getSubAppId()));
        }
        wxPayConfig.setSubMchId(StringUtils.trimToNull(payConfig.getSubMchId()));
        wxPayConfig.setKeyPath(StringUtils.trimToNull(payConfig.getCertPath()));

        // 可以指定是否使用沙箱环境
        wxPayConfig.setUseSandboxEnv(false);
        WxPayService wxPayService = new WxPayServiceImpl();
        wxPayService.setConfig(wxPayConfig);

        return wxPayService;
    }
    public static WxPayService getWxComplaintsV3PayService(PayConfig payConfig){
        WxPayConfig wxPayConfig = new WxPayConfig();
        wxPayConfig.setAppId(StringUtils.trimToNull(payConfig.getAppid()));
        wxPayConfig.setMchId(StringUtils.trimToNull(payConfig.getMchId()));
        wxPayConfig.setMchKey(StringUtils.trimToNull(payConfig.getWxKey()));
        if(StringUtils.isNotBlank(payConfig.getSubAppId())) {
            wxPayConfig.setSubAppId(StringUtils.trimToNull(payConfig.getSubAppId()));
        }
        wxPayConfig.setSubMchId(StringUtils.trimToNull(payConfig.getSubMchId()));
        wxPayConfig.setKeyPath(StringUtils.trimToNull(payConfig.getCertPath()));
        wxPayConfig.setTradeType(WxPayConstants.TradeType.JSAPI);
        wxPayConfig.setPrivateKeyPath(payConfig.getPrivateKeyPath());
        wxPayConfig.setCertSerialNo(payConfig.getCertSerialNo());
        wxPayConfig.setApiV3Key(payConfig.getWxKey());
        // 可以指定是否使用沙箱环境
        wxPayConfig.setUseSandboxEnv(false);
        WxPayService wxPayService = new WxPayServiceImpl();
        wxPayService.setConfig(wxPayConfig);


        return wxPayService;
    }

    /**
     * 构建微信APIV3接口  统一下单请求数据
     * @return
     */
    public static JSONObject buildV3OrderRequest(WxPayDto wxPayDto, PayConfig payConfig) {
        String payOrderId = wxPayDto.getResOrderNo();

        // 微信统一下单请求对象
        JSONObject reqJSON = new JSONObject();
        reqJSON.put("out_trade_no", payOrderId);
        reqJSON.put("description", wxPayDto.getBody());
        reqJSON.put("notify_url", payConfig.getNotifyUrl());

        JSONObject amount = new JSONObject();
        amount.put("total", Integer.parseInt(wxPayDto.getRealTotalMoney()));
        amount.put("currency", "CNY");
        reqJSON.put("amount", amount);

        JSONObject sceneInfo = new JSONObject();
        sceneInfo.put("payer_client_ip", payConfig.getSpbillCreateIp());
        reqJSON.put("scene_info", sceneInfo);

        //优惠功能
        if (wxPayDto.getProductId()!=null){
            JSONObject detail = new JSONObject();
            JSONArray goods_detail = new JSONArray();
            JSONObject goodsInfo = new JSONObject();
            goodsInfo.put("merchant_goods_id",wxPayDto.getProductId().toString());
            goodsInfo.put("quantity",1);
            goodsInfo.put("unit_price",Integer.parseInt(wxPayDto.getRealTotalMoney()));
            goods_detail.add(goodsInfo);
            detail.put("goods_detail",goods_detail);
            reqJSON.put("detail", detail);
        }


        if(StringUtils.isNotBlank(payConfig.getSubMchId())){ // 特约商户
            reqJSON.put("sp_appid", payConfig.getAppid());
            reqJSON.put("sp_mchid", payConfig.getMchId());
            reqJSON.put("sub_mchid", payConfig.getSubMchId());
            if (StringUtils.isNotBlank(payConfig.getSubAppId())) {
                reqJSON.put("sub_appid", payConfig.getSubAppId());
            }
        }else { // 普通商户
            reqJSON.put("appid", payConfig.getAppid());
            reqJSON.put("mchid", payConfig.getMchId());
        }

        return reqJSON;
    }

    /**
     * 获取微信响应
     *
     * @param request
     * @return
     * @throws IOException
     */
    public static String getWxRes(HttpServletRequest request) throws IOException {
        String resXml = "";
        InputStream inputStream = request.getInputStream();
        //将InputStream转换成xmlString
        BufferedReader reader = new BufferedReader(new InputStreamReader(inputStream));
        StringBuilder sb = new StringBuilder();
        String line = null;
        try {
            while ((line = reader.readLine()) != null) {
                sb.append(line + "\n");
            }
        } catch (IOException e) {
            System.out.println(e.getMessage());
        } finally {
            try {
                inputStream.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        resXml = sb.toString();
        return resXml;
    }

}
